import time
import smtplib
import logging
import platform
from imbox import Imbox
from datetime import datetime
from email.mime.text import MIMEText
from apscheduler.schedulers.blocking import BlockingScheduler

logging.basicConfig(level=logging.INFO,  # 控制台打印的日志级别
                    filename='new.log',
                    filemode='a',  # 模式，有w和a，w就是写模式，每次都会重新写日志，覆盖之前的日志
                    # a是追加模式，默认如果不写的话，就是追加模式
                    format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
                    # 日志格式
                    )


class EmailInfo():

    def __init__(self, imap_server_host, email_address, email_password, ssl=True):

        self.imap_server_host = imap_server_host
        self.email_address = email_address
        self.email_password = email_password
        self.ssl = ssl
        self.mail_host = "smtp.126.com"  # 设置服务器
        self.mail_user = "xxxxxxxx"  # 用户名
        self.mail_pass = "xxxxxxxxxxxx"  # 口令
        self.mail_postfix = "126.com"  # 发件箱的后缀
        self.mailto_list = ['','','']
        self.mailcc_list = ['xxxxxxxx@qq.com']
        self.command = ['当前时间', '系统信息', '当前用户']

    def filter_mail(self, title):

        with Imbox(imap_server_host, email_address, email_password, ssl=True, ssl_context=None,
                   starttls=False) as imbox:

            all_inbox_messages = imbox.messages(folder='warnning')

            for uid, message in all_inbox_messages:

                if message.subject.replace(': ', '：', 1) == title:
                    logging.info('已经搜索到指定的告警邮件 {}'.format(title))
                    if len(message.body['plain']):
                        res = message.body['plain'][0]
                        res = res.replace('\r\n', ' ').split()[0]
                        logging.info('subject: {}  回复命令是： {}'.format(
                            message.subject, res))

                        if self.filter_content(res):
                            print('发送成功')
                        else:
                            print('发送失败')

                logging.info(
                    '邮件UID: {} - SUBJECT: {}移动到收件箱移动到收件箱'.format(uid, message.subject))
                imbox.move(uid, 'inbox')

    def filter_content(self, res):
        rs = True
        if res not in self.command:
            if not self.send_mail(self.mailto_list, self.mailcc_list,
                                  '命令发送错误', '想好了再发！！！！！！！！！'):
                rs = False
                return rs
        if res == '当前时间':
            self.send_mail(self.mailto_list, self.mailcc_list, res,
                           '{}'.format(datetime.now()))
        if res == '系统信息':
            self.send_mail(self.mailto_list, self.mailcc_list, res,
                           '{}'.format(platform.uname()))
        if res == '当前用户':
            self.send_mail(self.mailto_list, self.mailcc_list, res,
                           '{}'.format('手动填写 win10 伪管理员'))
        return rs

    def send_mail(self, to_list, mailcc_list, sub, content):

        me = "hello"+"<"+self.mail_user+"@" + \
            self.mail_postfix+">"  # 这里的hello可以任意设置，收到信后，将按照设置显示
        # 创建一个实例，这里设置为html格式邮件
        msg = MIMEText(content, _subtype='html', _charset='gb2312')
        msg['Subject'] = sub  # 设置主题
        msg['From'] = me
        msg['To'] = ";".join(to_list)
        msg['Cc'] = ";".join(mailcc_list)
        try:
            s = smtplib.SMTP()
            s.connect(self.mail_host)  # 连接smtp服务器
            s.login(self.mail_user, self.mail_pass)  # 登陆服务器
            s.sendmail(me, to_list, msg.as_string())  # 发送邮件
            return True
        except (Exception):
            print("失败...")
            return False

        finally:
            s.close()


if __name__ == "__main__":

    email_address = "xxxxx@139.com"
    email_password = "xxxxxxxxx"
    imap_server_host = "imap.139.com"
    title = '回复：邮件告警：测试测试测试'

    ep = EmailInfo(email_address, email_password, imap_server_host)
    scheduler = BlockingScheduler()
    scheduler.add_job(ep.filter_mail, 'interval', seconds=30, args=[title])
    scheduler.start()
